<template>
  <div>
    <div ref="main" class="main">图表</div>
    <button @click="getData">getData</button>
  </div>
</template>

<script>
import * as echarts from "echarts";
import _ from "lodash";
export default {
  data() {
    return {
      chart: null,
      option: {
        title: {
          text: "ECharts 入门示例",
        },
        tooltip: {},
        xAxis: {
          data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
        },
        yAxis: {},
        series: [
          {
            name: "销量",
            type: "bar",
            data: [5, 20, 36, 10, 10, 20],
          },
        ],
      },
      data: [5, 20, 36, 10, 10, 20],
    };
  },
  watch: {
    option: {
      handler() {
        this.chart.setOption(this.option);
      },
      deep: true,
    },
  },
  mounted() {
    // 用ref获取dom元素， 把echarts实例放入data中实现响应式
    this.chart = echarts.init(this.$refs.main);
    // 绘制图表
    this.chart.setOption(this.option);
    window.addEventListener("resize", this.resize());
  },
  destroyed() {
    // addEventListener和removeEventListener必须要公用同一个执行函数，不能直接用箭头函数
    window.removeEventListener("resize", this.resize());
  },
  methods: {
    getData() {
      this.data = [
        _.random(5, 50),
        _.random(5, 50),
        _.random(5, 50),
        _.random(5, 50),
        _.random(5, 50),
        _.random(5, 50),
      ];
      this.option.series[0].data = this.data;
    },
    resize() {
      this.chart.resize();
    },
  },
};
</script>

<style>
.main {
  width: 50vw;
  height: 50vw;
}
</style>
